package com.jar.exercise.多线程.线程之间的通信;

import java.util.Objects;

/**
 * 模拟银行取钱的问题
 */
public class ThreadCommunication4 {
	public static void main(String[] args) {
		Account account = new Account("123456", 10000.0);
		UserThread thread1 = new UserThread("小明", account, 8000.0);
		UserThread thread2 = new UserThread("小红", account, 2500.0);
		thread1.start();
		thread2.start();
	}
}

class Account {
	private String accourntId;
	private Double balance;

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		Account account = (Account) o;
		return Objects.equals(accourntId, account.accourntId) &&
			Objects.equals(balance, account.balance);
	}

	@Override
	public int hashCode() {
		return Objects.hash(accourntId, balance);
	}

	public String getAccourntId() {
		return accourntId;
	}

	public void setAccourntId(String accourntId) {
		this.accourntId = accourntId;
	}

	public Double getBalance() {
		return balance;
	}

	public void setBalance(Double balance) {
		this.balance = balance;
	}

	public Account() {
	}

	public Account(String accourntId, Double balance) {
		this.accourntId = accourntId;
		this.balance = balance;
	}
}

class UserThread extends Thread {
	private final Account account;
	private Double banlance;

	/**
	 * @param name    线程名称
	 * @param account 账户信息
	 * @param balance 要取的金额
	 * @author ZhangShengHao
	 * @date 2020/2/8 15:47
	 */
	public UserThread(String name, Account account, Double balance) {
		super(name);
		this.banlance = balance;
		this.account = account;
	}

	@Override
	public void run() {
		synchronized (account) {
			try {
				if (banlance < account.getBalance()) {
					Thread.sleep(200);
					System.out.println(getName() + "：取走" + banlance + "元！");
					account.setBalance(account.getBalance() - banlance);
				} else {
					System.out.println(getName() + "：取钱失败，余额不足");
				}
				System.out.println("现在的余额为：" + account.getBalance());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
